<?php
/**
 * プッシュ送信コントローラー
 *
 * @package  app
 * @extends  Controller
 */
class Controller_Batch_Push extends Controller_Manage {
	/**
	 * 一括送信
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_bulk() {
		$start = time();
		for ($i = 0; $i < 20; $i++) {
			// 1分で切る
			$t = time() - $start;
			if ($t >= 60) {
				break;
			}

			// 最新のメッセージを取得
			$query = DB::select('push_id', 'push_text', 'create_date');
			$query -> from('push_bulk');
			$query -> where('del', '0');
			$query -> order_by('push_id', 'DESC');
			$query -> limit(1);
			$result = $query -> execute() -> as_array();
			if (count($result) == 0) {
				break;
			}
			$push_id = $result[0]['push_id'];
			$text = $result[0]['push_text'];

			// 対象の会員を抽出(優先)
			$query = DB::select('member_info.member_id', 'devicetoken');
			$query -> from('member_info');
			$query -> where('member_status', '0');
			$query -> where('push_enable', '1');
			$query -> where('devicetoken', '!=' , '');
			$query -> where('push_lastid', '<', $push_id);
			$query -> where('push_lastid', '>=', 0);
			$query -> limit(10);
			$query -> join('member_point','LEFT') -> on('member_point.member_id', '=', 'member_info.member_id');
			$query -> group_by('member_point.member_id');
			$query -> order_by('member_point.point_id', 'desc');
			$result = $query -> execute() -> as_array();
			if( count($result) == 0 ) {
				// 対象の会員を抽出(ランダム)
				$query = DB::select('member_id', 'devicetoken');
				$query -> from('member_info');
				$query -> where('member_status', '0');
				$query -> where('push_enable', '1');
				$query -> where('devicetoken', '!=' , '');
				$query -> where('push_lastid', '<', $push_id);
				$query -> where('push_lastid', '>=', 0);
				$query -> limit(10);
				$query -> order_by(DB::expr('RAND()'));
				$result = $query -> execute() -> as_array();
			}

			if (count($result) == 0) {
				break;
			}
			
			// プッシュ送信
			$messages = array();
			foreach ($result as $value) {
				$messages[] = array('token' => $value['devicetoken'], 'text' => $text);
			}
			$res = $this -> apns_push($messages);
			if ($res === true || is_array($res) ) {
				// 成功もしくは個別エラー
				// 送信済みフラグを立てる
				foreach ($result as $value) {
					$query = DB::update('member_info');
					$query -> set(array('push_lastid' => $push_id));
					$query -> where('member_id', $value['member_id']);
					$query -> execute();
				}
			} else {
				// エラー
				$token = str_replace('Invalid device token','',$res);
				$token = trim(str_replace("'",'',$token));
				
				// 消しこみ
				$query = DB::update('member_info');
				$query -> set(array('push_lastid' => -1));
				$query -> where('devicetoken', $token);
				$query -> execute();
			}
			if( $res !== true) {
				$this->alert( print_r($res, true) );
				sleep(1);
			}
						
		}

		return Response::forge('OK', D_HTTP_UPDATE);
	}

}
